/**
 * 参数操作工具类
 */

import { Context } from "koa";
import { ResultError, resultErrorJson, resultType } from "./resultError";

export type KeyValue = { [key: string]: unknown }


export enum CheckType {
  canEmpty, // 可以为空
  cantEmpty, // 不能为空
  checkName, // 验证名字格式
  checkPassword, // 验证密码格式
}

interface CtxParamKeys {
  keyname: string;
  checkType: CheckType;
}

export const getCtxParams = (
  ctx: Context,
  keys: CtxParamKeys[]
): { check: boolean; error: ResultError | null; params: { [k: string]: any } } => {
  let params = {} as { [k: string]: any };
  for (let i = 0; i < keys.length; i++) {
    const { keyname, checkType } = keys[i];
    const param = ctx.query[keyname];
    if (checkParam(param, checkType)) {
      params[keyname] = param;
    } else {
      return { check: false, error: checkParamError(ctx, checkType), params };
    }
  }
  return { check: true, error: null, params };
};

const checkParam = <T>(param: T, checkType: CheckType) => {
  switch (checkType) {
    case CheckType.cantEmpty:
      return !!param;
    default:
      return true;
  }
};

const checkParamError = (ctx: Context, checkType: CheckType) => {
  switch (checkType) {
    case CheckType.cantEmpty:
      return resultErrorJson(resultType.lossParam, "缺少参数");
    default:
      return resultErrorJson(resultType.unknown, "未知错误");
  }
};
